package com.example.demo.aop;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

/**
 * Created by lile on 2020-01-16.
 */
@Aspect
@Component
public class WebLoggerAspect {

    @Pointcut(value = "execution(*  com.example.demo..*.*(..))")
    public void pc() {
    }

    /**
     * 环绕通知
     *
     * @throws Throwable
     */
    @Around(value = "@annotation(webLog)")
    public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
        webLog systemLog = ((MethodSignature) pjp.getSignature()).getMethod().getAnnotation(webLog.class);
        System.out.println(systemLog.value());
        System.out.println(systemLog.id());
        System.out.println("环绕通知前*********************");
        //System.out.println(mytest.method() + "*********************8");
        Object tagert = pjp.proceed();
        System.out.println("环绕通知后*********************");



      //获取注解上的值如 : @MyAnnotation(key = "'param id is ' + #id")
        Method method = ((MethodSignature) pjp.getSignature()).getMethod();
        webLog annotation = method.getAnnotation(webLog.class);
        //将注解的值中的El表达式部分进行替换
        //创建解析器
        SpelExpressionParser parser = new SpelExpressionParser();
        //获取表达式
        String keyEl = annotation.id();
        Expression expression = parser.parseExpression(keyEl);
        //设置解析上下文(有哪些占位符，以及每种占位符的值)
        EvaluationContext context = new StandardEvaluationContext();
        //获取参数值
        Object[] args = pjp.getArgs();
        System.out.println(args.length);
        //获取运行时参数的名称
        DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
        String[] parameterNames = discoverer.getParameterNames(method);
        System.out.println(parameterNames.length);
        for (int i = 0; i < parameterNames.length; i++) {
            context.setVariable(parameterNames[i],args[i].toString());
        }
        String result = expression.getValue(context).toString();

        System.out.println(result);

        return tagert;
    }

//    @Around(value = "pc()")
//    public Object aroundMethodTest(ProceedingJoinPoint pjp) throws Throwable {
//
//        System.out.println("111");
//        Object tagert = pjp.proceed();
//        System.out.println("222");
//        return tagert;
//
//    }

}
